package spring.rabbitmq.producer;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import spring.rabbitmq.User;

import java.util.HashMap;

/**
 * 生产者
 *
 * @author ZCW
 * @createTime 2018/4/28
 * @lastUpdateTime 2018/4/28 ZCW
 */
@Component
public class Producer {

    // 该接口定义了一套针对AMQP协议的基础操作
    @Autowired
    AmqpTemplate amqpTemplate;

    public void sendHello() {
        String queue = RabbitMqConfig.HELLO;
        String msg = "Hello World!";
        System.out.println("---------------sendHello---------------");
        amqpTemplate.convertAndSend(queue, msg);
        System.out.println("---------------sendHello---------------");
    }

    public void sendObject() {
        String queue = RabbitMqConfig.OBJECT;
        System.out.println("---------------sendObject---------------");
        amqpTemplate.convertAndSend(queue, new User("小李",18));
        System.out.println("---------------sendObject---------------");
    }

    public void sendWorkQueues() {
        int time = (int) (Math.random() * 10);
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < time; i++) {
            sb.append(".");
        }

        String queue = RabbitMqConfig.WORKQUEUES;
        System.out.println("---------------sendWorkQueues---------------");
        amqpTemplate.convertAndSend(queue, sb.toString());
        System.out.println("---------------sendWorkQueues---------------");
    }

    /**
     * Publish/Subscribe
     * <p>
     * Sending messages to many consumers at once
     * 同时向许多消费者发送消息
     */
    public void sendExFanout() {
        System.out.println("---------------sendWorkQueues---------------");
        amqpTemplate.convertAndSend(RabbitMqConfig.LOGS, "", "test");
        System.out.println("---------------sendWorkQueues---------------");
    }
}
